<template>
  <div>
    <div class="app_card mb-2 pt-4 pb-4">

      <div class="d-flex justify-content-between search-form">
        <div class="flex-grow-1">
          <el-input class="w200px mr-3" v-model.trim="queryParam.name" autocomplete="off" placeholder="教室名称"/>
          <el-select class="w200px mr-3" v-model="queryParam.campusId" placeholder="全部校区">
            <el-option  label="全部校区" :value="null" />
            <el-option v-for="item in campusOption" :key="item.id" :label="item.Name" :value="item.id" />
          </el-select>
          <el-select class="w200px mr-3" v-model="queryParam.buildingId" placeholder="全部教学楼">
            <el-option  label="全部教学楼" :value="null" />
            <el-option v-for="item in buildingOption" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button type="primary"  @click="onRefresh()">搜索</el-button>
          <el-button type="primary" plain @click="onReset()">重置</el-button>
        </div>
        <div class="d-flex">
          <el-button type="primary" @click="onRestartMulti()">批量重启</el-button>
<!--          <el-button plain type="primary" @click="onStartRow()">录制开始</el-button>-->
<!--          <el-button plain type="primary" @click="onRestartEnd()">录制结束</el-button>-->
        </div>
      </div>

    </div>
    <div class="app_card pt-4  pb-5">
      <el-table stripe size="large" :data="dataOfTable" height="calc(100vh - 300px)" sortable="custom" @sort-change="handleSortChange" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column label="教室" prop="name" align="left">
          <template #default="scope">{{ scope.row.Name }}</template>
        </el-table-column>
<!--        <el-table-column label="教室状态" prop="onclass" align="left">-->
<!--          <template #default="scope">-->
<!--            <template v-if="scope.row.onclass=='0'">下课</template>-->
<!--            <template v-else-if="scope.row.onclass=='1'">上课</template>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="学院" prop="academyName" align="center">
          <template #default="scope">{{ scope.row.recordTask?.Course.Academy.name||scope.row.liveTask?.Course.Academy.name  }}</template>
        </el-table-column>
        <el-table-column label="课程名称" prop="courseName" align="center">
          <template #default="scope">{{ scope.row.recordTask?.Course.name||scope.row.liveTask?.Course.name }}</template>
        </el-table-column>
        <el-table-column label="教师姓名" prop="teacherName" align="center">
          <template #default="scope">{{  scope.row.recordTask?.Teacher.name||scope.row.liveTask?.Teacher.name }}</template>
        </el-table-column>
        <el-table-column label="录播主机IP" prop="recordingIp" align="center">
          <template #default="scope">{{ scope.row.recordingIp }}</template>
        </el-table-column>
        <el-table-column label="录播主机状态" prop="taskStatus" align="center">
          <template #default="scope">

            <div class="status-red dot"  v-if="scope.row.recordInfo?.recordingStatus === 1">离线</div>
            <div class="status-green dot" v-if="scope.row.recordInfo?.recordingStatus === 2">在线</div>
            <div class="status-grey dot"  v-if="!scope.row.recordInfo">不存在</div>
          </template>
        </el-table-column>
        <el-table-column label="录播状态" prop="taskStatus" align="center">
          <template #default="scope">
            <template  v-if="scope.row.recordTask">
              <div class="status-green dot" >录制中</div>
              <div>{{scope.row.recordTask.startTime.slice(0,5)}}-{{scope.row.recordTask.endTime.slice(0,5)}}</div>
            </template>
            <div class="status-grey dot" v-else>空闲</div>
          </template>
        </el-table-column>
        <el-table-column label="直播状态" prop="taskStatus" align="center">
          <template #default="scope">
            <div class="status-green dot" v-if="scope.row.liveTask">直播中</div>
            <div class="status-grey dot" v-else>空闲</div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120" align="left">
          <template #default="scope">
            <el-button link type="primary" v-if="scope.row.recordTask" @click="onStopRow(scope.row)">结束录制</el-button>
            <el-button link type="primary" v-if="scope.row.liveTask" @click="onStopLiveRow(scope.row)">结束直播</el-button>
<!--            <el-button link type="primary" v-else @click="onStartRow(scope.row)">开始录制</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="mt-2">
        <el-pagination background v-model:currentPage="queryParam.page" v-model:page-size="queryParam.pageSize" :page-sizes="paginationOption.pageSizes" :background="false" :layout="paginationOption.layout" :total="paginationOption.count" @size-change="handleChangeSize" @current-change="handleChangeCurrent" />
      </div>
    </div>
    <StartDialog ref="startDialogRef" @success="loadData()"></StartDialog>
  </div>
</template>

<script setup>
/**
 * 角色组件
 */
import { ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
//组件
import StartDialog from './StartDialog.vue';

// ======================================================
//                      变量声明
// ======================================================

// 组件引用
const startDialogRef = ref(null);
// 表格数据
const dataOfTable = ref([]);


const campusOption = ref([]);
const buildingOption = ref([]);

// 组件可视状态
const visibleState = ref({
  searchForm: true,
})
// 表格查询参数
const queryParam = ref({

  activityId: null,
  page: 1,
  pageSize: 10,
})
// 分页栏配置数据
const paginationOption = ref({
  layout: 'total, sizes, prev, pager, next, jumper',
  pageSizes: [10, 20, 50, 100, 500, 1000],
  count: 0,
})
// 表格多选数据
const multipleSelection = ref([]);

// ======================================================
//                      点击操作
// ======================================================

// 点击刷新按钮
const onRefresh = () => {
  queryParam.value.page = 1;
  loadData();
}

const onReset = () => {
  queryParam.value = {
    activityId: null,
    page: 1,
    pageSize: 10,
  }
  loadData()
}

const onStartRow = (row = null) => {
  console.log(row)
  startDialogRef.value.show(row?.id, '录制开始', row);
}
const onStopRow = (row) => {
  ElMessageBox.confirm("确定录制结束？", "警告",{
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        EsAjax.post(ApiUrls.recordingStop, {
          "id": row.recordTask?.id,
          "roomId":row.id,
          "recordIp":row.recordTask?.recordIp,
          "relaFileTaskId": row.recordTask?.relaFileTaskId,
          "endTime": row.recordTask?.endTime,
        })
            .then(res => {
              if (res.data.code !== 200) {
                ElMessage.warning(res.data.msg);
                return;
              }
              ElMessage.success("操作成功");
              loadData();
            })
            .catch(err => { ElMessage.error("网络错误：", err.message) })
            .finally(()=>{instance.confirmButtonLoading = false;done();});
      } else {
        done()
      }
    }
  })

}

const onStopLiveRow = (row) => {
  ElMessageBox.confirm("确定直播结束？", "警告",{
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        EsAjax.post(ApiUrls.liveStop, {
          "id": row.liveTask?.id,
          "roomId":row.id,
          "recordIp":row.recordTask?.recordIp,
          "relaFileTaskId": row.recordTask?.relaFileTaskId,
          "endTime": row.recordTask?.endTime,
        })
            .then(res => {
              if (res.data.code !== 200) {
                ElMessage.warning(res.data.msg);
                return;
              }
              ElMessage.success("操作成功");
              loadData();
            })
            .catch(err => { ElMessage.error("网络错误：", err.message) })
            .finally(()=>{instance.confirmButtonLoading = false;done();});
      } else {
        done()
      }
    }
  })

}

// 重启
const onRestartMulti = () => {
  let n = multipleSelection.value.length, ip = multipleSelection.value.map(v => v.recordingIp).toString();
  if (n) {
    ElMessageBox.confirm("确定重启 " + n + " 条记录吗？", "警告",{
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
            instance.confirmButtonLoading = true
            EsAjax.post(ApiUrls.recordingEquipmentRestart, { ip }).then(res => {
              if (res.data.code !== 200) {
                ElMessage.warning(res.data.msg);
                return;
              }
              ElMessage.success("操作成功");
              loadData();
          }).catch(err => {
            ElMessage.error("网络错误：" + err.message);
          }).finally(()=>{instance.confirmButtonLoading = false;done();});
        } else {
          done()
        }
      }
    })
  } else {
    ElMessage.info("请选择批量数据");
  }

}




// ======================================================
//                      处理事件
// ======================================================

// 处理表格全选
const handleSelectionChange = (val) => {
  console.log(val)
  multipleSelection.value = val
}

// 处理表格排序
const handleSortChange = (column) => {
  queryParam.value.orderby = column.prop + ' ' + (column.order == 'descending' ? 'desc' : 'asc');
  console.log(queryParam.value);
  loadData();
}

// 处理分页尺寸
const handleChangeSize = (val) => {
  console.log(`${val} items per page`);
  queryParam.value.page = 1;
  queryParam.value.pageSize = val;
  loadData();
}

// 处理页码
const handleChangeCurrent = (val) => {
  console.log(`current page: ${val}`)
  queryParam.value.page = val;
  loadData();
}

// ======================================================
//                      处理事件
// ======================================================

const loadData = () => {
  EsAjax.post(ApiUrls.roomInfoList, queryParam.value).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list, count } = res.data.data
    dataOfTable.value = list;
    paginationOption.value.count = count;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}




const getCampusList = () => {
  EsAjax.post(ApiUrls.campusList, { params: {} }).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    campusOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}

const getBuildingList = () => {
  EsAjax.post(ApiUrls.buildingList, { params: {} }).then(res => {
    if (res.data.code !== 200) {
      ElMessage.warning(res.data.msg);
      return;
    }
    let { list } = res.data.data
    buildingOption.value = list;
  }).catch(err => {
    ElMessage.error(err.message);
  })
}


loadData();

getCampusList();
getBuildingList();
</script>

